// 搜索防抖定时器
let searchTimer = null;

Page({
	data: {
		searchText: '',
		currentTab: 'all', // all | system | study | interaction
		isLoading: false,
		showDetailModal: false,
		selectedChat: null,
		messages: [],
		filtered: [],
		unreadCount: 0
	},

	onLoad() {
		this.bootstrap();
	},

	onShow() {
		this.bootstrap();
	},

	// 下拉刷新
	onPullDownRefresh() {
		this.bootstrap();
		setTimeout(() => {
			wx.stopPullDownRefresh();
			wx.showToast({
				title: '刷新成功',
				icon: 'success',
				duration: 1500
			});
		}, 1000);
	},

	bootstrap() {
		this.setData({ isLoading: true });
		try {
			// 读取本地存储，不存在则用示例数据填充
			let msgs = wx.getStorageSync('teacherMessages');
			if (!msgs || !Array.isArray(msgs) || msgs.length === 0) {
				msgs = this.sampleMessages();
				wx.setStorageSync('teacherMessages', msgs);
			}
			// 时间倒序
			msgs.sort((a, b) => new Date(b.timeISO) - new Date(a.timeISO));
			
			// 统计未读数量
			const unreadCount = msgs.filter(m => m.unread).length;
			
			this.setData({ 
				messages: msgs, 
				unreadCount,
				isLoading: false 
			});
			this.applyFilter();
		} catch (e) {
			this.setData({ isLoading: false });
			wx.showToast({ title: '加载失败', icon: 'none' });
		}
	},
	sampleMessages() {
		const now = new Date();
		const iso = (d) => new Date(d).toISOString();
		return [
			{ id: 'sys-1', type: 'system', title: '系统通知', content: '您的作业已批改完成，快来查看吧！', time: '10:30', timeISO: iso(now), unread: true },
			{ id: 'study-1', type: 'study', title: '学习提醒', content: '今日学习任务还未完成，继续加油！', time: '09:15', timeISO: iso(now - 2*60*60*1000), unread: true },
			{ id: 'im-1', type: 'interaction', title: '张老师', content: '你的数学作业完成得很好，继续保持！', time: '昨天', timeISO: iso(now - 24*60*60*1000), unread: false },
			{ id: 'sys-2', type: 'system', title: '版本更新', content: '新版本已发布，包含更多学习功能', time: '昨天', timeISO: iso(now - 26*60*60*1000), unread: false },
			{ id: 'study-2', type: 'study', title: '每日打卡', content: '恭喜你完成今日学习打卡！', time: '2天前', timeISO: iso(now - 48*60*60*1000), unread: false }
		];
	},
	// 搜索输入（带防抖）
	onSearchInput(e) {
		const searchText = e.detail.value;
		this.setData({ searchText });
		
		// 清除之前的定时器
		if (searchTimer) {
			clearTimeout(searchTimer);
		}
		
		// 设置新的定时器（300ms防抖）
		searchTimer = setTimeout(() => {
			this.applyFilter();
		}, 300);
	},

	// 清除搜索
	clearSearch() {
		this.setData({ searchText: '' });
		this.applyFilter();
	},
	applyFilter() {
		const s = (this.data.searchText || '').toLowerCase();
		let list = this.data.messages;
		if (this.data.currentTab !== 'all') {
			list = list.filter(m => m.type === this.data.currentTab);
		}
		if (s) {
			list = list.filter(m => (m.title && m.title.toLowerCase().includes(s)) || (m.content && m.content.toLowerCase().includes(s)));
		}
		this.setData({ filtered: list });
	},
	switchTab(e) {
		this.setData({ currentTab: e.currentTarget.dataset.tab });
		this.applyFilter();
	},
	// 显示消息详情
	showChatDetail(e) {
		const chat = e.currentTarget.dataset.chat;
		console.log('显示消息详情:', chat);
		this.setData({ 
			selectedChat: chat, 
			showDetailModal: true 
		});
	},

	// 隐藏详情弹窗
	hideChatDetail() {
		this.setData({ 
			showDetailModal: false, 
			selectedChat: null 
		});
	},

	// 标记已读并关闭
	markReadAndClose(e) {
		const chatId = e.currentTarget.dataset.id;
		if (chatId) {
			this.markRead(chatId);
			wx.showToast({
				title: '已标记为已读',
				icon: 'success',
				duration: 1500
			});
		}
		this.hideChatDetail();
	},

	// 继续对话/查看详情
	continueChat() {
		const chat = this.data.selectedChat;
		this.hideChatDetail();
		
		// 根据消息类型跳转到不同页面
		if (chat) {
			switch (chat.type) {
				case 'system':
					wx.showToast({ title: '系统通知详情（待接入）', icon: 'none' });
					break;
				case 'study':
					wx.showToast({ title: '学习提醒详情（待接入）', icon: 'none' });
					break;
				case 'interaction':
					wx.showToast({ title: '互动消息详情（待接入）', icon: 'none' });
					break;
				default:
					wx.showToast({ title: '查看详情（待接入）', icon: 'none' });
			}
		}
	},
	showDeleteOptions(e) {
		const chatId = e.currentTarget.dataset.id;
		wx.showActionSheet({
			itemList: ['删除消息', '设为已读'],
			success: (res) => {
				if (res.tapIndex === 0) {
					const chat = this.data.messages.find(x => x.id === chatId);
					this.confirmDeleteChat(chatId, (chat && chat.title) || '消息');
				} else if (res.tapIndex === 1) {
					this.markRead(chatId);
				}
			}
		});
	},
	confirmDeleteChat(chatId, title) {
		wx.showModal({
			title: '确认删除',
			content: `确定要删除“${title}”吗？`,
			confirmText: '删除',
			confirmColor: '#ff4757',
			success: (res) => { if (res.confirm) this.deleteById(chatId); }
		});
	},
	deleteChat(e) {
		const chatId = e.currentTarget.dataset.id;
		const chat = this.data.messages.find(x => x.id === chatId);
		if (!chat) { wx.showToast({ title: '消息不存在', icon: 'none' }); return; }
		this.confirmDeleteChat(chatId, chat.title || '消息');
	},
	deleteById(chatId) {
		try {
			const updated = this.data.messages.filter(c => c.id !== chatId);
			wx.setStorageSync('teacherMessages', updated);
			this.setData({ messages: updated });
			this.applyFilter();
			wx.showToast({ title: '删除成功', icon: 'success' });
		} catch (e) {
			wx.showToast({ title: '删除失败', icon: 'none' });
		}
	},
	// 标记单条消息已读
	markRead(chatId) {
		const msgs = this.data.messages.map(m => m.id === chatId ? { ...m, unread: false } : m);
		const unreadCount = msgs.filter(m => m.unread).length;
		wx.setStorageSync('teacherMessages', msgs);
		this.setData({ messages: msgs, unreadCount });
		this.applyFilter();
	},

	// 全部已读
	markAllRead() {
		if (this.data.unreadCount === 0) {
			wx.showToast({ title: '暂无未读消息', icon: 'none' });
			return;
		}
		const msgs = this.data.messages.map(m => ({ ...m, unread: false }));
		wx.setStorageSync('teacherMessages', msgs);
		this.setData({ messages: msgs, unreadCount: 0 });
		this.applyFilter();
		wx.showToast({ title: '已全部标记为已读', icon: 'success' });
	},

	// 清空所有消息
	clearAll() {
		if (this.data.messages.length === 0) {
			wx.showToast({ title: '暂无消息', icon: 'none' });
			return;
		}
		wx.showModal({
			title: '确认清空',
			content: '确定要清空所有消息吗？此操作不可恢复',
			confirmText: '清空',
			confirmColor: '#ff4757',
			success: (res) => { 
				if (res.confirm) {
					this.clearAllConfirm();
				}
			}
		});
	},
	clearAllConfirm() {
		try {
			wx.removeStorageSync('teacherMessages');
			this.setData({ messages: [], filtered: [], searchText: '', unreadCount: 0 });
			wx.showToast({ title: '已清空', icon: 'success' });
		} catch (e) {
			wx.showToast({ title: '清空失败', icon: 'none' });
		}
	},

	// 阻止冒泡
	stopPropagation() {
		// 空函数，用于阻止事件冒泡
	}
});



